<template>
	<view class="pointCenter">
    <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
    <view class="header">
      <view class="header_content">
        <view class="topUserInfo">
          <image class="avatarUrl" :src="userAvatarUrl ? userAvatarUrl : 'https://efc-public-assets-1252208446.cos.ap-shanghai.myqcloud.com/images/ugc/avatar.jpg'"></image>
          <view>
            <!--<view class="nickName point-num">{{filter.add_comma_toThousands(pointsOverview.pointsBalance ? pointsOverview.pointsBalance : 0)}}</view>-->
            <view class="userName">{{userNickName}}</view>
            <!--<view wx:if="{{showJoinMember == 1}}" class="nickNameBox member" @tap="joinMember">加入会员</view>-->
            <view v-if="showJoinMember == 0" class="pointsInfo">
              <view class="member-Level">会员等级：{{memberLevelName}}</view>
              <view class="member" @click="goPointsCenter">可用积分：{{filter.add_comma_toThousands(pointsOverview.pointsBalance ? pointsOverview.pointsBalance : 0)}}</view>
            </view>
          </view>
        </view>


        <view class="nickName">
          <view  class="nickName member" @click="pointsDetail"> 积分详情</view>
          <view  class="nickName member" @click="goCoupons">我的优惠</view>
          <view  class="nickName member" @click="memberGrowth">积分说明</view>
        </view>
      </view>
    </view>


    <view class="points-Block">
       <view class="points-gain">
         <view class="text">积分获取</view>
         <view class="points-image">
            <image src="https://efc-public-assets-1252208446.cos.ap-shanghai.myqcloud.com/images/points-gain_1.png" mode="widthFix" style="width: 100%;"></image>
           <view class="points-image-link">
              <view class="a1" @click="pointsDetail"></view>
              <view class="a2" @click="goUserCenter"></view>
              <view class="a3" @click="interactive"></view>
            </view>
         </view>
       </view>
	   <view class="pointsBox exchange">
	     <view class="text">限时积分兑礼</view>

	   		<view v-if="giftList.length > 0">
	   			<view class="img-box" v-for="(item, index) in giftList" :key="index">
	   				<view class="img-x">
	   				  <image :src="item.params.coverImg" class='imgge'></image >
	   				</view>
	   				<view class="text1">
	   				  <p style="text-align: center;">{{item.params.title}}</p>
	   				  <p class="p2" ><image src="https://www.cosstores.cn/img/dm/pageup/210114/jifen.png" class='imgge2' style="position: absolute;top: 16%;left: 36%;"></image><view class="points-text">{{item.pointsAmount}}</view></p>
	   				  <button class="button-x" @click="redeemGift(item.transactionTypeId)">即刻兑换</button>
	   				  <p style="margin-top: 18rpx;">{{filter.getRedeemGiftLevels(item.params.memberLevels)}}等级会员兑换</p>
	   				</view>
	   		  </view>
	   		</view>
	   		<view v-else>
	   			<image src="https://efs-cloud-miniprogram-store-1252208446.cos.ap-shanghai.myqcloud.com/images/cos-miniprogram/points-gains_1.png" mode="widthFix" style="width: 100%;"></image>
	   		</view>
	   </view>


       <view class="pointsBox exchange">
         <view class="text">限时积分兑券</view>
		 <view v-if="couponItems.length > 0">
			 <view class="exchange-content" v-for="(item, index) in couponItems" :key="index">
			   <view v-if="filter.expiredCoupon(item.endAt)"></view>
			  <view class="total">
				<view>
				  <view style="font-size: 34rpx; ">{{item.typeName}}</view>
				  {{item.typeSubtitle}}
				</view>
				<view class="nickName exchange-num point-num" @click="redeemCouponEvent(item.typeId)">{{filter.add_comma_toThousands(item.pointsAmount)}}积分</view>
				<view class="btn" @click="redeemCouponEvent(item.typeId)">即刻兑换</view>
			  </view>
			  <view class="tip">
				<view><lable class="frist">COS{{filter.couponChannels(item.channels)}}通用</lable><lable  class="second">{{item.typeDescription}}</lable> </view>
				<view><lable class="frist" v-if="item.memberLevels.length < 3">仅限{{filter.memberLevels(item.memberLevels)}}兑换</lable></view>
			  </view>
			 </view>
		 </view>
		 <view v-else class="points-gain">
			 <image src="https://efs-cloud-miniprogram-store-1252208446.cos.ap-shanghai.myqcloud.com/images/cos-miniprogram/points-gains_1.png" mode="widthFix" style="width: 100%;"></image>
		 </view>
      </view>

    </view>

    <!--兑换券成功弹层-->
    <view class="success-pop"  v-if="redeemCouponSuccess">
      <i class="iconfont icon-cuowu1" @click="closeBox"></i>
      <view class="goPoints">兑换成功！</view>
      <view class="goPoints">立即查看<text @click="goCoupons" class="underline">我的优惠</text></view>
    </view>

    <!--兑换券失败遮盖弹层-->
    <view class="bg" v-if="redeemCouponError || redeemCouponSuccess"></view>
    <!--兑换券失败弹层-->
    <view class="success-pop" v-if="redeemCouponError">
      <i class="iconfont icon-cuowu1" @click="closeBox"></i>
      <view class="goPoints">{{redeemErrorMsg}}</view>
      <view class="goPoints">立即查看<text @click="goCoupons" class="underline">我的优惠</text></view>
    </view>

    <!--敬请期待弹层-->
    <!-- <view class="success-pop"  v-if="showInteractive">
      <i class="iconfont icon-cuowu1" @click="closeBox"></i>
      <view class="goPoints">敬请期待</view>
    </view> -->

	</view>
</template>

<script module="filter" lang="wxs" src="../../../utils/filter.wxs"></script>
<script>
  import api from '@/api/api';
  import filter from '../../../utils/filter.wxs';
  import NavBar from '@/components/common/navbar';
  import {CUSTOMER_INFO, MEMBER_INFO, USER_INFO} from '../../../utils/constant';
	export default {
    components:{
      navBar:NavBar
    },
		data() {
			return {
				pointsOverview:[],
				couponItems:[],
				userAvatarUrl:'',
				redeemCouponSuccess : false,
				redeemCouponError : false,
				redeemErrorMsg:'兑换失败！请稍后重试或咨询客服',
				showInteractive:false,//限时互动
				memberLevelName: '',
				showJoinMember: -1, // 加入会员  1：显示, 0 隐藏
				userNickName: "",
				giftList:[],
        navbarData: {
          showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
          navbarTitle: '积分中心', //导航栏 中间的标题
          hideSearch:true,
          hideHome:true
        },
        isShowCustomNavBar: true,
        nowPages: '',
			}
		},
    onLoad() {
      let that = this;
      let userInfo = uni.getStorageSync(USER_INFO);
      that.userAvatarUrl = userInfo.avatarUrl;
      that.userNickName = userInfo.nickName;
	  let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
	  if (customerInfo) {
		  //积分
		  that.getMemberDetail();
		  that.pointsInfo();
		  that.couponList();
		  that.redeemListGift();
	  }else{
		  uni.navigateTo({
		  	url:'/pages/customer/customer'
		  });
	  }
    let pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    this.nowPages = currPage.route;
    },
    onShow() {
       let that = this;
       getApp().cl_tracker.track('mini_program_view', {
         path: this.nowPages,
         pageName: '积分中心',
       })
     },
	methods: {
      // 入会页
       goUserCenter(){
          uni.navigateTo({
            url:'/pages/customer/registerSetting'
          })
        },

        // 我的优惠
        goCoupons(){
          uni.navigateTo({
            url:'/pages/customer/couponList'
          })
        },

        interactive(){
          let that = this;
          // that.showInteractive = true;
		  uni.navigateTo({
		    url:'/pages/customer/points/points?source=pointsCenter'
		  })


        },

        redeemCouponEvent(typeId){
          let that = this;
          that.redeemCoupon(typeId);
        },

        obtainedPoints(){
          let that = this;
          that.obtainedTab = true;
          that.usedTab = false;
        },

        usedPoints(){
          let that = this;
          that.usedTab = true;
          that.obtainedTab = false;
        },
        pointsDetail(){
          uni.navigateTo({
            url:'/pages/points/points'
          })
        },

        memberGrowth(){
          uni.navigateTo({
            url:'/pages/cms/page?identifier=cms/vipbanner'
          })
        },

        closeBox(){
          let that = this;
          that.redeemCouponSuccess = false;
          that.redeemCouponError = false;
          that.showInteractive = false;
        },

		redeemListGift:async function(){
			let that = this;
			let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
			const parmas = {
			  filter: 'Available',
			}
			const giftList = await api.redeemListGift({
			  header: {jwt: customerInfo.jwt},
				query: parmas
			});
			if (giftList.code === 1000) {
			    that.giftList = giftList.data;
			}else if(giftList.msg == 'jwt验证失败'){
				uni.navigateTo({
					url:'/pages/info'
				});
			}
		},
		redeemGift(typeId){
			uni.navigateTo({
			  url:'/pages/points/redeemGift?type_id='+typeId
			})
		},

      /**
       * 判断是否是会员
       *
       * @param jwt
       * @return {Promise<void>}
       */
      getMemberDetail: async function(jwt) {
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
        const memberDetailsResult = await api.getMemberDetails({
          header: {jwt: customerInfo.jwt},
        })
        if(memberDetailsResult.code == 1000){
          const phoneNumberReg = /^1\d{10}$/;
          if(!phoneNumberReg.test(memberDetailsResult.data.mobile)){
            // 非大陆手机号按照非会员对待,重新入会
            uni.removeStorageSync('memberDetails');
            that.showJoinMember = 1;
            return;
          }
          that.memberDetails = memberDetailsResult.data;
          if(that.memberDetails.isActive == "Inactive"){
            that.showJoinMember = 1;
          }else{
            that.showJoinMember = 0;
            that.showGetCoupon = 0;
            that.memberLevelName = that.memberDetails.memberLevel.levelName;
            that.memberLevelId = that.memberDetails.memberLevel.memberLevelId;
          }
          uni.setStorageSync(MEMBER_INFO, {memberLevelId:that.memberDetails.memberLevel.memberLevelId,isActive:that.memberDetails.isActive});
        }else{
          that.showJoinMember = 1;
   
        }
      },


       couponList: async function(){
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
        const json = await api.redeemListCoupon({
          header: {'jwt': customerInfo.jwt},
        });

        if (json.code === 1000) {
            that.couponItems = json.data;
        }
      },


      getPointsTransaction: async function(currentPage){
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
        const parmas = {
          page: currentPage,
          size: that.pageSize,
          sort: 'CreatedAt',
          sort_dir: 'DESC'
        }

        const json = await api.pointsTransaction({
          header: {'jwt': customerInfo.jwt},
          query: parmas
        });
        if (json.code === 1000) {
          let data = json.data.data;
          that.pageTotal = data.totalPages;
          that.pointsList = [...that.pointsList, ...data.content];
        }
      },


      /**
       * 积分总览
       * */
      pointsInfo: async function(){
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
        const json = await api.pointsInfo({
          header: {'jwt': customerInfo.jwt},
        });
        if (json.code === 1000) {
          that.pointsOverview = json.data;
        }
      },

      /**
       * 兑换券
       * */
      redeemCoupon:async function(typeId){
        let that = this;
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO) || {};
        const json = await api.redeemCoupon({
          header: {'jwt': customerInfo.jwt},
          method: 'POST',
          query: {
            typeId: typeId,
          }
        });
        if (json.code === 1000) {
          that.redeemCouponSuccess = true;
          that.pointsInfo();
        }else{
          that.redeemCouponError = true;
          if(json.code === -1006){
            that.redeemErrorMsg = '你的会员等级不符，暂不可兑';
          }else if(json.code === -1007){
            that.redeemErrorMsg = '积分余额不足，暂不可兑';
          }else if(json.code === -1008){
            that.redeemErrorMsg = '活动尚未开启，敬请期待';
          }
        }
      },



      //加载更多
      onReachBottom() {
        let that = this;
        //判断总页数是否大于翻页数
        if ((that.pageTotal) > that.currentPage) {
          //防止重复加载
          if (that.preventRepeatReuqest) {
            return true;
          }
          that.preventRepeatReuqest = true;
          that.currentPage++;
          that.getPointsTransaction(that.currentPage);
          that.preventRepeatReuqest = false;
        }
      },

      onPullDownRefresh() {
        wx.showNavigationBarLoading();    //在当前页面显示导航条加载动画
        this.pointsList = [];
        this.currentPage = 1;
        this.getPointsTransaction(this.currentPage);
        setTimeout(function () {
          wx.hideNavigationBarLoading();    //在当前页面隐藏导航条加载动画
          wx.stopPullDownRefresh();    //停止下拉动作
        }, 2000)
      },


		}
	}
</script>

<style lang="less">
.pointsBox{
  .total{display:flex;justify-content:space-between;}
  .total label{display: block;font-size:56rpx;line-height: 60rpx;}
  .tip view{font-size:22rpx;}
  .btn{
    background-color: #444;color:#fff;
    width:170rpx;height: 56rpx;
    line-height: 56rpx;margin-top: 32rpx;
  }
}
.tabTitle{display: flex;border-top:2rpx solid #ccc;}
.tabTitle label{width:50%;text-align: center;padding:16rpx 0;background-color:#eee;color:#999;border-bottom:2rpx solid #ccc;}
.tabTitle label:first-child{border-right:2rpx solid #ccc;}
.tabTitle label.act{color:#333;background-color: #fff;border-bottom:none;}

.tabMain{margin-bottom:100rpx;}
.tabMain .item{padding:24rpx 40rpx;border-bottom:2rpx solid #ccc;}
.tabMain .item .h5{display: flex;justify-content: space-between;margin-bottom:14rpx;font-size:30rpx;}
.tabMain .item .time{color:#999;}
.header {
  height: 350rpx;
  width: 750rpx;
  display: flex;
  align-items: center;
  background-image: url('https://efc-public-assets-1252208446.cos.ap-shanghai.myqcloud.com/images/crm/2020011519589.jpg');
  background-repeat: no-repeat;
  background-size: 100% 100%;
}
.header_content {
  width: 100%;
  text-align: center;
}
.nickName {
  font-size: 30rpx;
  color: #fff;
  text-align: center;
  display: block;
  margin: 20rpx auto 0;
}
.member {
  text-decoration: underline;
  color: #fff;
  display: inline-block;
  padding: 0 40rpx;
}
.topUserInfo .member{
  padding:0;
  text-decoration: none;
  text-align: left;
}
.pointsInfo{
  text-align: left;
}
.avatarUrl {
  width: 118rpx;
  height: 118rpx;
  display: block;
  border-radius: 1000px;
  margin-right:50rpx;
}
.point-num{
  background-repeat: no-repeat;
  background-size: 5%;
  background-position: 45% center;
  padding-left: 60rpx;
  background-image: url('https://efs-cloud-miniprogram-store-1252208446.cos.ap-shanghai.myqcloud.com/images/cos-miniprogram/point-icon.png');
}
.pointsBox .total {
  display: flex;
  justify-content: space-between;
  padding-top: 30rpx;
  line-height: 46rpx;
}
.pointsBox .total label {
  display: block;
  font-size: 56rpx;
  line-height: 60rpx;
}
.pointsBox .btn {
  background-color: #444;
  color: #fff;
  width: 170rpx;
  height: 56rpx;
  line-height: 56rpx;
  margin-top: 38rpx;
}
.pointsBox .tip {
  margin-top: 36rpx;
}
.points-Block{
  background: #f0f0f0;
  width: 750rpx;
  padding-bottom: 50rpx;
}
.points-Block .text{
padding: 40rpx 30rpx;
font-size: 34rpx;
  }
.exchange-content{
  padding: 0 75rpx;
  background-image: url('https://efs-cloud-miniprogram-store-1252208446.cos.ap-shanghai.myqcloud.com/images/cos-miniprogram/coupon.png');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  height: 230rpx;
  position: relative;
  margin-bottom:10rpx;
}
  .exchange-num{
    color: #444444;
    position: absolute;
    top: 9%;
    margin: 0;
    right: 10%;
    background-size: 22%;
    background-position: 30% center;
    width: 170rpx;
    text-align: center;
    /*background-image: url('https://efs-cloud-miniprogram-store-1252208446.cos.ap-shanghai.myqcloud.com/images/cos-miniprogram/point-b.png');*/
  }
  .tip .second{
    float: right;
  }
.success-pop{
  border: 1px solid #eee;
  position: absolute;
  width: 400rpx;
  text-align: center;
  padding: 30px;
  top: 50%;
  background: #fff;
  z-index: 2;
  left: 50%;
  transform: translate(-50%, 0);

}
.success-pop .iconfont{
  position: absolute;
  padding: 15rpx 15rpx 30rpx 30px;
  cursor: pointer;
  right: 0;
  top: 0;
}
.goPoints{
  line-height: 25px;
}
.bg{
  background-color: rgba(0, 0, 0, 0.5);
  position: fixed;
  width: 100vw;
  height: 100vh;
  left: 0;
  top: 0;
  z-index: 1;
}
  .points-gain{
    position: relative;
  }
.points-gain  .map{
  width: 22%;
  height: 34%;
  bottom: 13%;
  right: 39%;
  position: absolute;
  z-index: 1;
}
  .underline{
    text-decoration: underline;
  }
  .points-image{position: relative;padding: 0 35rpx;}
  .points-image-link{position: absolute;left:35rpx;top:0;width:92.2%;height:100%;display: flex;}
  .points-image-link view{width:33.33%;}
.avatarUrlImg {
  width: 100rpx;
  height: 100rpx;
  border-radius: 1000px;
}
.userName{color:#fff;text-align: left;}
.member-Level{color:#fff;margin: 6rpx 0;}
.topUserInfo{display: flex;padding:0 0 30rpx 120rpx;}
.redeem-button{
	background-color: #444;
	width: 100%;
	height: 50rpx;
	color:#FFFFFF;
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 24rpx;
	margin-top: 20rpx;
}
</style>
<style>
  .img-box{display:flex;justify-content: center; margin: 20rpx 35rpx;background-color: #FFFFFF;}
  .img-x{width: 205rpx; height: 205rpx;margin: 25rpx;}
  .imgge{width: 205rpx; height:205rpx;}
  .text1{margin: 0 auto;margin-top: 33rpx;text-align: center;}
  .text1 .p2{margin-top: 12rpx;position: relative;}
  .text1 .p2 .imgge2{background: #f0f0f0;width: 25rpx; height:25rpx;}
  .button-x{background-color: #444;width: 160rpx; height: 50rpx; color:#FFFFFF;font-size: 24rpx;margin-top: 12rpx;line-height: 50rpx;}
  .points-text{text-align: center;    width: 368rpx}
</style>
